<template>
  <el-dialog title="" width="800px" :close-on-click-modal="false" :visible.sync="visible" center="">
    <div data-v-2c844fd9="" class="title-line"><span class="tit" style="font-size: 38px;">登录</span></div>
    <div class="login-box">
      <div class="login-left">
        <img src="../../assets/img/logo-vertical.png" alt="" class="login-logo" />
      </div>
      <div class="line"></div>
      <div class="login-right" :class="type == 1 ? 'padding-top-80' : 'padding-top-30'">
        <el-form
          :model="loginDataForm"
          :rules="loginDataRule"
          ref="loginDataForm"
          @keyup.enter.native="LoginSubmit()"
          label-width="0px"
          v-show="type == 1"
        >
          <div class="type-tab">
            <span :class="loginType == 1 ? 'active' : ''" @click="loginType = 1">密码登录</span>
            <span :class="loginType == 2 ? 'active' : ''" @click="loginType = 2">短信登录</span>
          </div>
          <el-form-item label="" prop="phone">
            <el-input class="with100" placeholder="填写常用手机号" v-model="loginDataForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="" v-show="loginType == 1" prop="password">
            <el-input class="with100" placeholder="密码" show-password v-model="loginDataForm.password"></el-input>
          </el-form-item>
          <el-form-item label="" v-show="loginType == 2" prop="code">
            <el-input placeholder="请输入短信验证码" v-model="loginDataForm.code">
              <el-button class="el-btn-main" type="primary" slot="append" @click="GetPhoneCode(1)" :disabled="disabled">
                {{ codeText }}
              </el-button>
            </el-input>
          </el-form-item>
          <div class="btn-box">
            <el-button class="with50 el-btn-main" type="primary" @click="LoginSubmit()">登录</el-button>
            <el-button class="with50" @click="type = 2">去注册</el-button>
          </div>
          <div class="third-party-box">
            <img class="wx-login" src="../../assets/img/wx.png" alt="" title="微信登录" @click="WXLogin" />
          </div>
        </el-form>
        <el-form
          :model="registerDataForm"
          :rules="registerDataRule"
          ref="registerDataForm"
          @keyup.enter.native="registerSubmit()"
          label-width="0px"
          v-show="type == 2"
        >
          <el-form-item label="" prop="nickName">
            <el-input class="with100" placeholder="昵称" v-model="registerDataForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input class="with100" placeholder="密码" show-password v-model="registerDataForm.password"></el-input>
          </el-form-item>
          <el-form-item label="" prop="phone">
            <el-input class="with100" placeholder="填写常用手机号" v-model="registerDataForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="" prop="code">
            <el-input placeholder="请输入短信验证码" v-model="registerDataForm.code">
              <el-button class="el-btn-main" type="primary" slot="append" @click="GetPhoneCode(2)" :disabled="disabled">
                {{ codeText }}
              </el-button>
            </el-input>
          </el-form-item>
          <div class="btn-box">
            <el-button class="with50 el-btn-main" type="primary" @click="registerSubmit()">
              注册
            </el-button>
            <el-button class="with50" @click="type = 1">去登陆</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <!-- <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span> -->
  </el-dialog>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import { refenceHeaders, getwxpcAppId } from 'api/http/request'
import { RegisterApi, LoginApi, GetCodeApi, GetUserInfoApi } from 'api/draft'
export default {
  components: {},
  /** 定义属性 */
  data() {
    var validatePhone = (rule, value, callback) => {
      if (value) {
        if (!this.$PhoneUtils.isPhoneNum(value)) {
          callback(new Error('手机号格式错了呀'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入注册时用的手机号呀'))
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (this.loginType == 1) {
        if (value) {
          callback()
        } else {
          callback(new Error('你没输入密码么？'))
        }
      } else {
        callback()
      }
    }
    var validateCode = (rule, value, callback) => {
      if (this.loginType == 2) {
        if (value) {
          callback()
        } else {
          callback(new Error('短信验证码不能为空哦'))
        }
      } else {
        callback()
      }
    }
    var validatePhone2 = (rule, value, callback) => {
      if (value) {
        if (!this.$PhoneUtils.isPhoneNum(value)) {
          callback(new Error('手机号格式错了呀'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入手机号呀'))
      }
    }
    var validatePassword2 = (rule, value, callback) => {
      if (value) {
        if (!this.$StringUtils.password(value)) {
          callback(new Error('密码设置复杂一点呀(特殊字符、数字和字母)'))
        }
        callback()
      } else {
        callback(new Error('请输入密码呀'))
      }
    }
    return {
      visible: false,
      //登录类型1密码登录2验证码登录
      loginType: 1,
      //弹框类型1登录2注册
      type: 1,
      loginDataForm: {
        code: null,
        password: '',
        phone: ''
      },
      loginDataRule: {
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'blur' }]
      },
      registerDataForm: {
        code: null,
        password: '',
        phone: '',
        nickName: ''
      },
      registerDataRule: {
        phone: [{ validator: validatePhone2, trigger: 'blur' }],
        password: [{ validator: validatePassword2, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        nickName: [{ required: true, message: '请告诉我你的昵称吧', trigger: 'blur' }]
      },
      codeText: '获取验证码',
      time: 0,
      disabled: false,
      ROOT_URL: this.$GLOBAL.ROOT_URL
    }
  },
  /** 计算属性，会监听依赖属性值随之变化 */
  computed: {},
  /** 监控data中的数据变化 */
  watch: {},
  /** 方法集合 */
  methods: {
    /**
     * 初始化数据
     */
    init(type) {
      this.visible = true
      this.type = type
      if (localStorage.CodeEndTime) {
        this.time = Math.round(this.$DateUtils.datedifference(localStorage.CodeEndTime, new Date()) / 1000)
        this.timer()
      }
    },
    /**
     * 登录
     */
    LoginSubmit() {
      this.$refs['loginDataForm'].validate(valid => {
        if (valid) {
          var param = {
            phone: this.loginDataForm.phone
          }
          switch (this.loginType) {
            case 1:
              param.password = md5(this.loginDataForm.password)
              param.code = ''
              break
            case 2:
              param.password = ''
              param.code = this.loginDataForm.code
              break
          }
          LoginApi(param)
            .then(res => {
              if (res.code == 0) {
                this.visible = false
                localStorage.setItem('token', res.msg)
                refenceHeaders()
                GetUserInfoApi()
                  .then(res => {
                    if (res.code == 0) {
                      this.$store.commit('SET_USER_INFO', res.data)
                      localStorage.setItem('ud', res.data.id)
                      localStorage.setItem('un', res.data.nickname ? res.data.nickname : '')
                      localStorage.setItem('up', '113646' + res.data.phone)
                      localStorage.setItem('uh', res.data.headUrl)
                      localStorage.setItem('us', res.data.state)
                      this.$emit('loginSuccess')
                    } else {
                    }
                  })
                  .catch(err => {
                    window.console.log(err)
                  })
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              window.console.log(err)
            })
        }
      })
    },
    /**
     * 注册
     */
    registerSubmit() {
      this.$refs['registerDataForm'].validate(valid => {
        if (valid) {
          var param = {
            code: this.registerDataForm.code,
            password: md5(this.registerDataForm.password),
            phone: this.registerDataForm.phone,
            nickName: this.registerDataForm.nickName
          }
          RegisterApi(param)
            .then(res => {
              if (res.code == 0) {
                this.$message({
                  message: '注册成功',
                  type: 'success'
                })
                this.loginDataForm.phone = this.registerDataForm.phone
                this.type = 1
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              window.console.log(err)
            })
        }
      })
    },
    /**
     * 获取验证码
     */
    GetPhoneCode(type) {
      var param = { type: type, phone: type == 1 ? this.loginDataForm.phone : this.registerDataForm.phone }
      GetCodeApi(param)
        .then(res => {
          if (res.code == 0) {
            this.time = 60
            this.timer()
            var now = new Date()
            var endTime = new Date(now.setMinutes(now.getMinutes() + 1))
            localStorage.setItem('CodeEndTime', endTime)
          } else {
            this.$message.error(res.msg)
          }
        })
        .then(() => {})
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    /**
     * 计时器
     */
    timer() {
      if (this.time > 0) {
        this.disabled = true
        this.time--
        this.codeText = this.time + '秒'
        setTimeout(this.timer, 1000)
      } else {
        this.time = 0
        this.codeText = '获取验证码'
        this.disabled = false
        localStorage.removeItem('CodeEndTime')
      }
    },
    WXLogin() {
      // 获取页面url
      var local
      local = encodeURIComponent(window.location.origin + this.ROOT_URL + localStorage.path)
      var appid = getwxpcAppId()
      var code = this.getUrlCode().code // 截取code
      if (code == null || code === '' || code == undefined) {
        window.location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`
      }
    },
    /** 获取url中的code */
    getUrlCode() {
      // 截取url中的code方法'
      var url = location.href
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf('?') != -1) {
        var str = url.substr(1)
        var strs = str.split('?')
        if (strs.length >= 2) {
          var strs = strs[1].split('&')
          for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
          }
        } else {
          return theRequest
        }
      }
      return theRequest
    }
  },
  /** 生命周期 - 创建完成（可以访问当前this实例） */
  created() {},
  /** 生命周期 - 挂载完成（可以访问DOM元素） */
  mounted() {},
  /** 生命周期 - 创建之前 */
  beforeCreate() {},
  /** 生命周期 - 挂载之前 */
  beforeMount() {},
  /** 生命周期 - 更新之前 */
  beforeUpdate() {},
  /** 生命周期 - 更新之后 */
  updated() {},
  /** 生命周期 - 销毁之前 */
  beforeDestroy() {},
  /** 生命周期 - 销毁完成 */
  destroyed() {},
  /** 如果页面有keep-alive缓存功能，这个函数会触发 */
  activated() {}
}
</script>

<style lang="scss" scoped>
.title-line {
  width: 750px;
  height: 28px;
  margin: 0 auto;
  border-bottom: 1px solid #ddd;
  margin-bottom: 28px;
  text-align: center;
  .tit {
    height: 56px;
    line-height: 56px;
    margin: 0 auto;
    padding: 0 20px;
    font-size: 40px;
    background: #fff;
    text-align: center;
  }
}
.login-box {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  position: relative;
  width: 700px;
  margin: 0 auto;
  .login-left {
    width: 350px;
    .login-logo {
      width: 100%;
    }
  }
  .line {
    border-right: 1px solid #ddd;
    height: 300px;
    margin-top: 28px;
  }
  .login-right {
    padding-left: 45px;
    width: 350px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    .type-tab {
      cursor: pointer;
      -webkit-box-pack: start-end;
      -webkit-justify-content: start-end;
      -moz-box-pack: start-end;
      -ms-flex-pack: start-end;
      justify-content: start-end;
      -webkit-box-align: center;
      -webkit-align-items: center;
      -moz-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      margin-bottom: 12px;
      display: -webkit-box;
      display: -webkit-flex;
      display: -moz-box;
      display: -ms-flexbox;
      display: flex;
      span {
        font-size: 14px;
        color: #555;
        letter-spacing: 0;
        margin-right: 20px;
      }
    }
    .type-tab > span.active {
      color: #00b1d8;
    }
  }
  .padding-top-80 {
    padding-top: 80px;
  }
  .padding-top-30 {
    padding-top: 30px;
  }
  .btn-box {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -moz-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-align-content: center;
    -ms-flex-line-pack: center;
    align-content: center;
  }
  .third-party-box {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -moz-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-align-content: center;
    -ms-flex-line-pack: center;
    align-content: center;
    padding-top: 10px;
    .wx-login {
      cursor: pointer;
    }
  }
}
</style>
